package com.kg.module.jtnc.nhdagl.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kg.core.annotation.AutoOperateLog;
import com.kg.core.annotation.NoRepeatSubmit;
import com.kg.core.exception.BaseException;
import com.kg.core.web.ResponseResult;
import com.kg.module.jtnc.jy.entity.KrJy;
import com.kg.module.jtnc.jy.service.KrJyService;
import com.kg.module.jtnc.nczdagl.entity.KrNczdagl;
import com.kg.module.jtnc.nhdagl.dto.KrNhdaglDTO;
import com.kg.module.jtnc.nhdagl.dto.NhzzjhjxxxDTO;
import com.kg.module.jtnc.nhdagl.dto.convert.KrNhdaglConvert;
import com.kg.module.jtnc.nhdagl.entity.KrNhdagl;
import com.kg.module.jtnc.nhdagl.service.KrNhdaglService;
import com.kg.module.jtnc.nzffthgl.entity.KrNzffthgl;
import com.kg.module.jtnc.nzffthgl.service.KrNzffthglService;
import com.kg.module.jtnc.nzxx.entity.KrNzxx;
import com.kg.module.jtnc.nzxx.service.KrNzxxService;
import com.kg.module.jtnc.rghs.entity.KrRghs;
import com.kg.module.jtnc.rghs.service.KrRghsService;
import com.kg.module.jtnc.rwgl.entity.KrRwgl;
import com.kg.module.jtnc.rwgl.service.KrRwglService;
import com.kg.module.jtnc.zzjh.entity.KrZzjh;
import com.kg.module.jtnc.zzjh.service.KrZzjhService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javafx.scene.control.ColorPicker;
import org.aspectj.weaver.ast.Var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 农户档案管理表 前端控制器
 * </p>
 *
 * @author xxx
 * @since 2024-11-02
 */
@RestController
@RequestMapping("/jtnc/nhdagl/krNhdagl")
@Api(tags = "农户档案管理表", value = "农户档案管理表", description = "KrNhdaglController")
public class KrNhdaglController {

    @Resource
    private KrNhdaglService krNhdaglService;
    @Resource
    private KrNhdaglConvert krNhdaglConvert;
    @Resource
    private KrZzjhService krZzjhService;

    @Resource
    private KrJyService krJyService;
    @Resource
    private KrRwglService krRwglService;
    @Resource
    private KrRghsService krRghsService;
    @Resource
    private KrNzffthglService krNzffthglService;
    @Resource
    private KrNzxxService krNzxxService;

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/select", value = "农户主下拉", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nhxm", value = "农户姓名", paramType = "query", required = false, dataType = "String")
    })
    @GetMapping("/select")
    public List<KrNhdagl> select(@RequestParam(value = "nhxm", required = false) String nhxm) {
        List<KrNhdagl> list = krNhdaglService.lambdaQuery()
                .like(StrUtil.isNotBlank(nhxm), KrNhdagl::getNhxm, nhxm)
                .orderByDesc(KrNhdagl::getCreateTime).list();
        return list;
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/selectZzjh", value = "根据农户查询种植计划", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nhId", value = "农户ID", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份", paramType = "query", required = true, dataType = "String")
    })
    @GetMapping("/selectZzjh")
    public List<KrZzjh> selectZzjh(@RequestParam String nhId, @RequestParam String year) {
        List<KrZzjh> list = krZzjhService.lambdaQuery()
                .eq(KrZzjh::getNhId, nhId)
                .eq(KrZzjh::getJhnd, year)
                .orderByAsc(KrZzjh::getSzzqKs).list();
        return list;
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/jxxx", value = "查询绩效信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "zzjhId", value = "种植计划ID", paramType = "query", required = true, dataType = "String")
    })
    @GetMapping("/jxxx")
    public NhzzjhjxxxDTO jxxx(@RequestParam String zzjhId) {
        KrZzjh byId = krZzjhService.getById(zzjhId);
        NhzzjhjxxxDTO nhzzjhjxxxDTO = BeanUtil.copyProperties(byId, NhzzjhjxxxDTO.class);
        List<KrJy> jyList = krJyService.lambdaQuery().eq(KrJy::getZzjhId, zzjhId).list();
        Double sumJyje = jyList.stream().collect(Collectors.summingDouble(KrJy::getJyje));
        Double sumSjzl = jyList.stream().collect(Collectors.summingDouble(KrJy::getSjzl));
        nhzzjhjxxxDTO.setSjzl(sumSjzl);
        nhzzjhjxxxDTO.setJyje(sumJyje);
        List<KrRwgl> rwlist = krRwglService.lambdaQuery().eq(KrRwgl::getZzjhId, zzjhId).list();
        nhzzjhjxxxDTO.setRwsl(rwlist.size());
        Integer collect = rwlist.stream().collect(Collectors.summingInt(i -> Integer.valueOf(i.getFs())));
        nhzzjhjxxxDTO.setRwfs(collect);
        List<KrRghs> listRg = krRghsService.lambdaQuery().eq(KrRghs::getZzjhId, zzjhId).list();
        Double sumYgfy = listRg.stream().collect(Collectors.summingDouble(t -> Double.valueOf(t.getYgfy())));
        nhzzjhjxxxDTO.setRghsf(sumYgfy);
        List<KrNzffthgl> listNzff = krNzffthglService.lambdaQuery().eq(KrNzffthgl::getZzjhId, zzjhId).list();
        Map<String, List<KrNzffthgl>> nzffMap = listNzff.stream().collect(Collectors.groupingBy(KrNzffthgl::getNzId));
        for (String s : nzffMap.keySet()) {
            KrNzxx nzxx = krNzxxService.getById(s);
            List<KrNzffthgl> nzffList = nzffMap.get(s);
            NhzzjhjxxxDTO.Nzsyxx nzxxDTO = BeanUtil.copyProperties(nzxx, NhzzjhjxxxDTO.Nzsyxx.class);
            Integer collect1 = nzffList.stream().collect(Collectors.summingInt(
                    i -> i.getType().equals("2") ? -i.getNzsl() : i.getNzsl()
            ));
            nzxxDTO.setNzsl(collect1);
        }
        return nhzzjhjxxxDTO;
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/setJsjb", value = "设置技术级别", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nhId", value = "ID", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "jsjb", value = "技术级别", paramType = "query", required = true, dataType = "String")
    })
    @GetMapping("/setJsjb")
    public void setJsjb(@RequestParam String nhId, @RequestParam String jsjb) {
        krNhdaglService
                .lambdaUpdate()
                .set(KrNhdagl::getJsjb, jsjb)
                .eq(KrNhdagl::getNhId, nhId)
                .update();
    }


    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/getById", value = "详情-农户档案管理表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nhId", value = "ID", paramType = "query", required = true, dataType = "String")
    })
    @GetMapping("/getById")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:getById')")
    public KrNhdaglDTO getById(String nhId) {
        return krNhdaglConvert.entityToDto(krNhdaglService.getById(nhId));
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/list", value = "分页列表-农户档案管理表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页条数", paramType = "query", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "params", value = "查询条件", paramType = "query", required = false, dataType = "String")
    })
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:list')")
    public Page<KrNhdaglDTO> list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                                  @RequestParam(value = "params", required = false) String params) {
        return krNhdaglService.pagelist(page, limit, params);
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/add", value = "新增-农户档案管理表", httpMethod = "POST")
    @ApiImplicitParams({})
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:add')")
    @NoRepeatSubmit
    @AutoOperateLog(logMethod = "/jtnc/nhdagl/krNhdagl/add", logMsg = "新增-农户档案管理表")
    public void add(@RequestBody KrNhdaglDTO krNhdaglDTO) throws BaseException {
        try {
            krNhdaglService.add(krNhdaglDTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage() != null ? e.getMessage() : "新增失败！请重试");
        }
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/update", value = "修改-农户档案管理表", httpMethod = "POST")
    @ApiImplicitParams({})
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:update')")
    @NoRepeatSubmit
    @AutoOperateLog(logMethod = "/jtnc/nhdagl/krNhdagl/update", logMsg = "修改-农户档案管理表")
    public void update(@RequestBody KrNhdaglDTO krNhdaglDTO) throws BaseException {
        try {
            krNhdaglService.update(krNhdaglDTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage() != null ? e.getMessage() : "修改失败！请重试");
        }
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/delete", value = "删除-农户档案管理表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nhIds", value = "待删除id列表", paramType = "body", required = true, allowMultiple = true, dataType = "String")
    })
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:delete')")
    @NoRepeatSubmit
    @AutoOperateLog(logMethod = "/jtnc/nhdagl/krNhdagl/delete", logMsg = "删除-农户档案管理表")
    public void delete(@RequestBody String[] nhIds) throws BaseException {
        try {
            krNhdaglService.delete(Arrays.asList(nhIds));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage() != null ? e.getMessage() : "删除失败！请重试");
        }
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/export/excel", value = "导出excel-农户档案管理表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "查询条件", paramType = "query", required = false, dataType = "String")
    })
    @GetMapping("/export/excel")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:export:excel')")
    public String exportExcel(@RequestParam(value = "params", required = false) String params) throws BaseException {
        String result = krNhdaglService.exportExcel(params);
        if ("error".equals(result)) {
            throw new BaseException("导出Excel失败，请重试！");
        }
        return result;
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/import/excel", value = "导入excel-农户档案管理表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求", paramType = "query", required = false, dataType = "HttpServletRequest")
    })
    @PostMapping("/import/excel")
    @PreAuthorize("hasAuthority('jtnc:nhdagl:krNhdagl:import:excel')")
    @NoRepeatSubmit
    @AutoOperateLog(logMethod = "/jtnc/nhdagl/krNhdagl/import/excel", logMsg = "导入excel-农户档案管理表")
    public ResponseResult importExcel(HttpServletRequest request) throws BaseException {
        try {
            String result = krNhdaglService.importExcel(request);
            if (StringUtils.hasText(result)) {
                // 导入失败，返回错误提示信息
                return ResponseResult.builder().code("200").message(result).build();
            } else {
                return ResponseResult.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage() != null ? e.getMessage() : "导入Excel失败，请重试！");
        }
    }

    @ApiOperation(notes = "/jtnc/nhdagl/krNhdagl/import/downloadTemplate", value = "下载导入模板-农户档案管理表", httpMethod = "GET")
    @GetMapping("/import/downloadTemplate")
    public String downloadTemplate() throws BaseException {
        String result = krNhdaglService.downloadTemplate();
        if ("error".equals(result)) {
            throw new BaseException("下载导入模板失败，请重试！");
        }
        return result;
    }
}
